<template>
  <view class="image-generator-container">
    <view class="title">
      <text class="title-line">穆夏风 AI图像生成</text>
      <!-- <text class="title-line">AI图像生成</text> -->
    </view>
    
    <view class="form-group">
      <text class="label">上传个人图像</text>
      <view class="upload-area" @click="choosePersonalImage">
        <image :src="personalImage" :class="['preview-image', { 'preset-image': isPresetPersonal }]" mode="aspectFit"></image>
      </view>
    </view>

    <view class="form-group">
      <text class="label">上传展览图像</text>
      <view class="upload-area" @click="chooseExhibitionImage">
        <image :src="exhibitionImage" :class="['preview-image', { 'preset-image': isPresetExhibition }]" mode="aspectFit"></image>
      </view>
      <button class="import-existing-btn" @click.stop="openImportFromExisting">从已有展览导入</button>
    </view>

    <button 
      class="generate-btn" 
      :loading="isGenerating" 
      :disabled="!canGenerate"
      @click="generateImage"
    >
      {{ isGenerating ? '生成中...' : '立即生成' }}
    </button>

    <view class="error-message" v-if="errorMessage">
      {{ errorMessage }}
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { uploadImages, imageAnalysis, generateImages, isLoggedIn, getCurrentUserId } from '@/services/api/backendApi';

// 响应式数据
// 预设图片（可直接用于风格化，不必上传）
const PRESET_PERSON = { id: 4, url: 'https://douyin-ai.tos-cn-shanghai.volces.com/ebd23e78-dd59-4f45-a142-490c4c80f3b5.jpg' };
const PRESET_EXHIB = { id: 5, url: 'https://douyin-ai.tos-cn-shanghai.volces.com/b5db4e5f-5561-458c-9f7e-ab0760974d47.png' };

// 预览图初始为预设图片
const personalImage = ref(PRESET_PERSON.url);
const exhibitionImage = ref(PRESET_EXHIB.url);

// 记录是否使用预设图片（用于UI显示）
const isPresetPersonal = ref(true);
const isPresetExhibition = ref(true);

const isGenerating = ref(false);
const resultImages = ref([]);
const errorMessage = ref('');
// 跳转从已有展览导入
function openImportFromExisting() {
  uni.navigateTo({ url: '/pages/image-import/exhibition-image-selector' });
}

// 展览选择相关数据（保留selectedExhibition用于导入模式）
const selectedExhibition = ref(null);

// 计算属性：是否可以生成
const canGenerate = computed(() => {
  // 如果有选择的展览，可以生成
  if (selectedExhibition.value) {
    return true;
  }
  
  // 如果使用预设图片，也可以生成（不需要展览）
  if (isPresetPersonal.value && isPresetExhibition.value) {
    return true;
  }
  
  return false;
});

// 选择个人图像
function choosePersonalImage() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const filePath = res.tempFilePath || (res.tempFilePaths && res.tempFilePaths[0]);
      console.log('选择个人图像结果:', res);
      console.log('获取到的文件路径:', filePath);
      
      if (!filePath) {
        errorMessage.value = '获取图片路径失败，请重试';
        return;
      }
      
      personalImage.value = filePath;
      isPresetPersonal.value = false;
      errorMessage.value = '';
    },
    fail: (err) => {
      console.error('选择个人图像失败:', err);
      errorMessage.value = `选择个人图像失败: ${err.errMsg}`;
    }
  });
}

// 选择展览图像
function chooseExhibitionImage() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const filePath = res.tempFilePath || (res.tempFilePaths && res.tempFilePaths[0]);
      console.log('选择展览图像结果:', res);
      console.log('获取到的文件路径:', filePath);
      
      if (!filePath) {
        errorMessage.value = '获取图片路径失败，请重试';
        return;
      }
      
      exhibitionImage.value = filePath;
      isPresetExhibition.value = false;
      errorMessage.value = '';
    },
    fail: (err) => {
      console.error('选择展览图像失败:', err);
      errorMessage.value = `选择展览图像失败: ${err.errMsg}`;
    }
  });
}

// 生成图像
async function generateImage() {
  if (!personalImage.value || !exhibitionImage.value) {
    errorMessage.value = '请先上传个人图像和展览图像';
    return;
  }
  
  // 只有在非预设图片模式下才需要选择展览
  if (!selectedExhibition.value && !(isPresetPersonal.value && isPresetExhibition.value)) {
    errorMessage.value = '请先选择或创建展览';
    return;
  }

  isGenerating.value = true;
  errorMessage.value = '';
  resultImages.value = [];

  try {
    console.log('=== 开始AI图像生成流程 ===');
    console.log('个人图像:', personalImage.value);
    console.log('展览图像:', exhibitionImage.value);
    console.log('选择的展览:', selectedExhibition.value);
    console.log('展览记录ID:', selectedExhibition.value?.recordId || '预设模式');
    
    // 1. 上传图片/或使用预设ID
    let uploadResult;
    
    // 判断是否使用预设图片：根据标志判断
    const usePresetPersonal = isPresetPersonal.value;
    const usePresetExhibition = isPresetExhibition.value;
    
    console.log('📤 步骤1: 处理图片上传');
    console.log('使用预设个人图片:', usePresetPersonal);
    console.log('使用预设展览图片:', usePresetExhibition);
    
    if (usePresetPersonal && usePresetExhibition) {
      // 两个都使用预设图片 - 直接使用固定ID，无需上传
      console.log('🎯 使用预设图片固定ID，无需上传');
      console.log('预设个人图片ID:', PRESET_PERSON.id);
      console.log('预设展览图片ID:', PRESET_EXHIB.id);
      
      uploadResult = { 
        portraitImageId: PRESET_PERSON.id, 
        exhibitionImageIds: [PRESET_EXHIB.id] 
      };
      console.log('✅ 预设图片ID准备完成:', uploadResult);
    } else {
      // 需要上传图片
      // 必须绑定到具体展览
      if (!selectedExhibition.value || !selectedExhibition.value.recordId) {
        console.warn('⚠️ 未选择展览，阻止上传');
        uni.showToast({ title: '请先选择或创建展览', icon: 'none' })
        isGenerating.value = false
        return
      }
      console.log('📤 开始上传图片到服务器，recordId =', selectedExhibition.value.recordId);
      uploadResult = await uploadImages(
        personalImage.value,
        [exhibitionImage.value],
        selectedExhibition.value.recordId
      );
      console.log('✅ 图片上传成功:', uploadResult);
    }

    // 2. 图片分析
    console.log('🔍 步骤2: 开始图片分析');
    const analysisResult = await imageAnalysis(
      uploadResult.portraitImageId,
      uploadResult.exhibitionImageIds
    );
    console.log('✅ 图片分析成功:', analysisResult);
    console.log('分析ID:', analysisResult.analysisId);

    // 3. 生成风格化图片 - 使用 generateImages API
    console.log('🎨 步骤3: 开始生成风格化图片');
    console.log('使用分析ID:', analysisResult.analysisId);
    
    const generateResult = await generateImages(analysisResult.analysisId);
    console.log('✅ 图片生成成功:', generateResult);
    console.log('生成图片数量:', generateResult.images ? generateResult.images.length : 0);

    // 4. 处理生成结果并跳转
    console.log('📋 步骤4: 处理生成结果');
    if (generateResult.images && generateResult.images.length > 0) {
      // 构造图片数据，包含收藏状态和来源信息
      const imagesData = generateResult.images.map((img, index) => ({
        imageId: img.imageId,
        imageUrl: img.imageUrl,
        isFavorite: false, // 默认未收藏
        exhibitionId: selectedExhibition.value?.recordId || 'preset_mode', // 绑定到展览记录或预设模式
        exhibitionName: selectedExhibition.value?.title || '预设图片生成',
        galleryName: selectedExhibition.value?.galleryName || '系统预设',
        // 标记图片来源
        sourceType: usePresetPersonal && usePresetExhibition ? 'preset' : 'uploaded',
        isPreset: usePresetPersonal && usePresetExhibition, // 是否使用了预设图片
        ownerType: usePresetPersonal && usePresetExhibition ? 'system' : 'user' // 所有者类型
      }));
      
      console.log('📋 构造的图片数据:', imagesData);
      
      // 跳转到结果页面，传递图片数据
      uni.navigateTo({
        url: `/pages/image-result/image-result?images=${encodeURIComponent(JSON.stringify(imagesData))}&exhibitionId=${selectedExhibition.value?.recordId || 'preset_mode'}`
      });
      
      console.log('✅ 跳转到结果页面完成');
    } else {
      throw new Error('未生成任何图片');
    }

  } catch (error) {
    console.error('❌ 图像生成流程失败:', error);
    errorMessage.value = `生成失败: ${error.message}`;
    uni.showToast({
      title: '生成失败',
      icon: 'none'
    });
  } finally {
    isGenerating.value = false;
  }
}

// 页面加载时处理参数
onLoad((query) => {
  console.log('ImageGenerator页面加载参数:', query);
  
  if (query.mode === 'preset') {
    // 预设图片模式
    console.log('进入预设图片模式');
    personalImage.value = PRESET_PERSON.url;
    exhibitionImage.value = PRESET_EXHIB.url;
    isPresetPersonal.value = true;
    isPresetExhibition.value = true;
    selectedExhibition.value = null;
  } else if (query.mode === 'import' && query.images && query.exhibition) {
    // 导入模式
    console.log('进入图片导入模式');
    try {
      const importedImages = JSON.parse(decodeURIComponent(query.images));
      const exhibitionData = JSON.parse(decodeURIComponent(query.exhibition));
      
      console.log('导入的图片:', importedImages);
      console.log('展览数据:', exhibitionData);
      
      // 设置展览信息
      selectedExhibition.value = exhibitionData;
      
      // 如果有导入的图片，使用第一张作为展览图片
      if (importedImages.length > 0) {
        exhibitionImage.value = importedImages[0];
        isPresetExhibition.value = false;
        isPresetPersonal.value = true; // 个人图片仍使用预设
      }
      
      uni.showToast({
        title: `已导入${importedImages.length}张图片`,
        icon: 'success'
      });
    } catch (e) {
      console.error('解析导入数据失败:', e);
      uni.showToast({
        title: '导入数据解析失败',
        icon: 'none'
      });
    }
  }
});
</script>

<style lang="scss">
.image-generator-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  padding: 20px;
  box-sizing: border-box;
}

.title {
  text-align: center;
  margin-bottom: 14px;
  
  .title-line {
    display: block;
    color: #ffffff;
    font-family: 'Fugaz One', 'PingFang SC', 'Microsoft YaHei', sans-serif;
    
    &:first-child {
      font-size: 32px;
      font-weight: bold;
      margin-bottom: 8px;
    }
    
    &:last-child {
      font-size: 18px;
      color: #cccccc;
    }
  }
}

.form-group {
  margin-bottom: 25px;
}

.label {
  display: block;
  color: #ffffff;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  font-family: 'Fugaz One', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.upload-area {
  position: relative;
  background: #2a2a2a;
  border: 2px dashed #555555;
  border-radius: 15px;
  width: 100%;
  height: 200px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0;
  text-align: center;
  box-sizing: border-box;
  transition: all 0.3s ease;
  
  &:active {
    border-color: #d4f4ed;
    background: rgba(15, 253, 205, 0.08);
  }
}

.preview-image {
  display: block;
  width: 100%;
  height: 100%;
  border-radius: 10px;
  margin: 0 auto;
  
  &.preset-image {
    opacity: 0.8;
    filter: grayscale(20%);
  }
}

.upload-placeholder {
  flex: 1;
  .upload-text {
    display: block;
    color: #ffffff;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 5px;
    font-family: 'Fugaz One', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
  
  .upload-subtext {
    display: block;
    color: #999999;
    font-size: 14px;
  }
}

@media (max-width: 360px) {
  .preview-image { width: 100%; }
}

.import-existing-btn {
  width: 100%;
  margin-top: 10px;
  background: #0FFDCD;
  color: #0c0c0c;
  border: none;
  border-radius: 10px;
  padding: 10px 16px;
  font-size: 14px;
  font-weight: 600;
  font-family: 'Fugaz One', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  transition: all 0.2s ease;
  &::after { border: none; }
  &:active { transform: translateY(1px); background: #0ee8be; }
}

.generate-btn {
  width: 100%;
  background: #e5f9f5;
  color: #ffffff;
  border: none;
  border-radius: 12px; /* 减小圆角使按钮变扁 */
  padding: 10px 30px; /* 减少上下内边距使按钮变扁 */
  font-size: 16px;
  font-weight: 600;
  font-family: 'Fugaz One', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  margin-top: 15px;
  transition: all 0.3s ease;
  /* 多层次阴影效果 */
  box-shadow: 
    0 4px 15px rgba(206, 247, 239, 0.3),  /* 主要阴影 */
    0 8px 30px rgba(197, 250, 239, 0.2);  /* 次要阴影 */
  
  &:active {
    transform: translateY(2px);
    background: #d1f6ee;
    box-shadow: 
      0 2px 8px rgba(188, 239, 229, 0.3),   /* 按下状态的主要阴影 */
      0 4px 15px rgba(184, 240, 229, 0.2);  /* 按下状态的次要阴影 */
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    
    &:active {
      transform: none;
    }
  }
}

.error-message {
  background: rgba(255, 0, 0, 0.1);
  border: 1px solid rgba(255, 0, 0, 0.3);
  color: #ff6b6b;
  padding: 12px 15px;
  border-radius: 10px;
  margin-top: 20px;
  font-size: 14px;
  text-align: center;
}
</style>